import { Button, Checkbox, Form, Input, message } from 'antd';
import React, { useState } from 'react';
import { history, useDispatch } from 'umi';

import type { Dispatch } from 'umi';

import { namespace } from '@/models/global';
import { getErrorMsg, handleCountDown } from '@/util/utils';

import styles from './index.less';

import wechatPic from '../../../assets/images/wechat.png';
interface Props {
  switchTabPage: (arg0: number) => void;
}
interface Register {
  password: string;
  passwordConfirm: string;
  name: string;
  companyName: string;
  mobileNo: string;
  mobileVerifyCode: string;
  email: string;
  callback: string;
}
const RegisterForm: React.FC<Props> = (props: Props) => {
  const [form] = Form.useForm();
  const [verificationCode, setVerificationCode] = useState(false);
  const [checked, setChecked] = useState(true);
  const [registerLoading, setRegisterLoading] = useState(false);
  const [countDownSecond, setCountDownSecond] = useState(60);
  const dispatch = useDispatch<Dispatch>();
  const onFinish = (values: Register) => {
    setRegisterLoading(true);
    console.log('Received values of form: ', values);
    dispatch({
      type: `${namespace}/register`,
      payload: {
        ...values,
        callback: window.location.origin + '/ConfirmEmail',
      },
      callback: async (res: any) => {
        if (res.code === 200) {
          setRegisterLoading(false);
          setTimeout(() => {
            history.push('Login');
            message.success('注册成功！请登录');
          }, 100);
        } else {
          message.error(getErrorMsg(res));
          setRegisterLoading(false);
        }
      },
    });
  };
  const registerWithQrcode = () => {
    return message.info('暂未开放');
    props.switchTabPage(0);
  };
  const getCode = () => {
    const mobileNo = form.getFieldValue('mobileNo');
    const pattern = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
    if (!!mobileNo && pattern.test(mobileNo)) {
      setVerificationCode(true);
      handleCountDown(60, setCountDownSecond, setVerificationCode);
    } else {
      message.error('手机号有误！');
      return;
    }
    dispatch({
      type: `${namespace}/sendSmsCode`,
      payload: {
        mobileNo,
      },
      callback: (res: any) => {
        if (res.code === 200) {
          message.success('获取验证码成功！');
        } else {
          message.error(getErrorMsg(res));
        }
      },
    });
  };
  const handleAgree = (e: any) => {
    setChecked(!e.target.checked);
  };
  return (
    <div className={styles.registerForm}>
      <div className={styles.title}>用户注册</div>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{}}
        onFinish={onFinish}
        form={form}
      >
        <Form.Item name="companyName" rules={[{ required: true, message: '请输入服务企业全称!' }]}>
          <Input placeholder="请输入服务企业全称（必填）" />
        </Form.Item>
        <Form.Item name="email" rules={[{ pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '邮箱格式不正确' }]}>
          <Input placeholder="请输入邮箱（选填）" />
        </Form.Item>
        <Form.Item name="mobileNo" rules={[{ required: true, message: '请输入手机号!' }]}>
          <Input placeholder="请输入手机号（必填）" />
        </Form.Item>
        <Form.Item name="mobileVerifyCode" rules={[{ required: true, message: '请输入验证码!' }]}>
          <Input
            placeholder="请输入验证码（必填）"
            suffix={
              <div
                style={
                  verificationCode
                    ? { pointerEvents: 'none', cursor: 'pointer' }
                    : { cursor: 'pointer' }
                }
                onClick={getCode}
                className={styles.getCode}
              >
                <span>|</span> &nbsp;
                {verificationCode ? (
                  `${countDownSecond}秒后重发`
                ) : (
                  <span className={styles.getCodeColor}>获取验证码</span>
                )}
              </div>
            }
          />
        </Form.Item>
        <Form.Item name="name" rules={[{ required: true, message: '请输入姓名!' }]}>
          <Input placeholder="请输入姓名（必填）" />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
          <Input type="password" placeholder="请输入密码（必填）" />
        </Form.Item>
        <Form.Item
          name="passwordConfirm"
          rules={[
            { required: true, message: '请再次输入密码!' },
            ({ getFieldValue }) => ({
              validator(role: any, value: string) {
                if (value !== getFieldValue('password')) {
                  return Promise.reject('密码不一致');
                }
                return Promise.resolve();
              },
            }),
          ]}
        >
          <Input type="password" placeholder="请再次输入密码（必填）" />
        </Form.Item>
        <Form.Item valuePropName="checked" noStyle>
          <Checkbox onChange={handleAgree}> </Checkbox>
            <span className={styles.agree}>
              <span>阅读并同意</span>{' '}
              <span onClick={() => window.open('Agreement?id=1')} className={styles.agreement}> &nbsp;服务协议 &nbsp;</span>
              <span>和</span>
              <span onClick={() => window.open('Agreement?id=0')} className={styles.agreement}> &nbsp;隐私协议</span>
            </span>

        </Form.Item>
        <Form.Item>
          <Button
            disabled={checked}
            style={{ width: '100%', marginTop: '32px' }}
            type="primary"
            htmlType="submit"
            loading={registerLoading}
          >
            注册
          </Button>
        </Form.Item>
        <Form.Item>
          <div className={styles.bottomAction}>
            <div onClick={() => history.push('Login')} className={styles.goLogin}>
              <span style={{ color: 'rgba(0, 0, 0, 0.45)' }}>已有账号？</span>去登陆
            </div>
            <div onClick={registerWithQrcode} className={styles.wechat}>
              <img src={wechatPic} alt="" />
              使用微信注册
            </div>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
};
export default RegisterForm;
